<!-- src/views/operations/TargetProductSelection.vue -->
<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="80%"
    @close="handleClose"
  >
    <div class="target-product-selection-container">
      <!-- 搜索区域 -->
      <div class="search-toolbar">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.title" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品编码">
            <el-input v-model="searchForm.code" placeholder="请输入商品编码" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- SKU列表 -->
      <el-table
        :data="skuList"
        v-loading="loading"
        row-key="id"
        @selection-change="handleSelectionChange"
        height="400"
      >
        <el-table-column type="selection" width="55" :selectable="checkSelectable" />
        <el-table-column prop="code" label="商品编码" />
        <el-table-column prop="title" label="商品名称" />
        <el-table-column prop="supplierName" label="供应商" />
      </el-table>

      <!-- 分页 -->
      <el-pagination
        layout="prev, pager, next, jumper, ->, total"
        :current-page="pagination.page"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        @current-change="handlePageChange"
        style="margin-top: 15px; text-align: right;"
      />
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { getSkuDtoListApi } from '@/api/sku'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['confirm', 'close'])

// 弹窗状态
const visible = ref(false)

// 弹窗标题
const title = ref('选择目标商品')

// SKU列表数据
const skuList = ref([])
const loading = ref(false)
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = ref({
  title: '',
  code: ''
})

// 选中的SKU
const selectedSkus = ref([])

// 选择模式（single-单选，multiple-多选）
const selectionMode = ref('multiple')

// 打开弹窗
const open = (options = {}) => {
  title.value = options.title || '选择目标商品'
  selectionMode.value = options.selectionMode || 'multiple'
  visible.value = true
  getSkuList()
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  emit('close')
}

// 确认选择
const handleConfirm = () => {
  if (selectedSkus.value.length === 0) {
    ElMessage.warning('请至少选择一个商品')
    return
  }
  
  // 处理选中的数据，添加目标数量和目标库位字段
  const selectedData = selectedSkus.value.map(item => ({
    ...item,
    targetCount: 1, // 默认数量为1
    targetLocation: '' // 默认库位为空
  }))
  
  emit('confirm', selectedData)
  handleClose()
}

// 获取SKU列表
const getSkuList = async () => {
  loading.value = true
  try {
    const res = await getSkuDtoListApi(
      pagination.value.page,
      pagination.value.pageSize,
      searchForm.value.title,
      searchForm.value.code
    )
    skuList.value = res.data.rows
    pagination.value.total = res.data.total
  } catch (error) {
    ElMessage.error('获取SKU列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.page = 1
  getSkuList()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    title: '',
    code: ''
  }
  pagination.value.page = 1
  getSkuList()
}

// 分页变化
const handlePageChange = (page) => {
  pagination.value.page = page
  getSkuList()
}

// 处理选择变化
const handleSelectionChange = (val) => {
  // 如果是单选模式，只保留最后一个选择的项
  if (selectionMode.value === 'single') {
    selectedSkus.value = val.length > 0 ? [val[val.length - 1]] : []
  } else {
    selectedSkus.value = val
  }
}

// 检查是否可选择（用于表格选择控制）
const checkSelectable = (row, index) => {
  // 可以添加额外的选择条件
  return true
}

// 暴露方法
defineExpose({
  open,
  close: handleClose
})
</script>

<style scoped>
.target-product-selection-container {
  padding: 10px;
}

.search-toolbar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 15px;
}

.search-form :deep(.el-form-item__label) {
  font-weight: normal;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>